﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Catalogo.Portable.Model;
using Catalogo.Windows8.Common;
using Catalogo.Portable.ViewModel;
using Catalogo.Portable.ViewModel.Messages;

namespace Catalogo.Windows8.Views
{
    public sealed partial class HomePage : LayoutAwarePage
    {
        public HomePage()
        {
            this.InitializeComponent();
        }

        public HomePageViewModel ViewModel
        {
            get
            {
                if (this.DefaultViewModel.ContainsKey("ViewModel"))
                {
                    return this.DefaultViewModel["ViewModel"] as HomePageViewModel;
                }
                return null;
            }
            set { this.DefaultViewModel["ViewModel"] = value; }
        }

        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (ViewModel == null)
            {
                ViewModel = new HomePageViewModel();
                ViewModel.Messenger.Subscribe<NavegarParaPagina>(NavegarParaPaginaMessageHandler.NavegarParaPagina);
                await ViewModel.LoadAsync();
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            ViewModel.Messenger.Unsubscribe<NavegarParaPagina>(NavegarParaPaginaMessageHandler.NavegarParaPagina);
        }

        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var item = (Item)e.ClickedItem;
            ViewModel.AbrirItemCommand.Execute(item.Id);
        }
    }
}
